package com.devin.controller;

import com.devin.pojo.Product;
import com.devin.service.ProductService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    @Qualifier("productService")
//    @Resource(name = "productService")
    private ProductService productService;

    @RequestMapping("/getAllProducts")
    public ModelAndView findProducts(@RequestParam(value = "page",defaultValue = "1")Integer page,
                                     @RequestParam(value = "size",defaultValue = "5")Integer size) {
        List<Product> allProducts = productService.findAllProducts(page,size);
        PageInfo<Product> productPageInfo = new PageInfo<>(allProducts);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("productPageInfo", productPageInfo);
        modelAndView.setViewName("products-list");
        return modelAndView;
    }

    @RequestMapping(value = "/addProduct", method = RequestMethod.POST)
    public String addProduct(Product product) {
        productService.addProduct(product);
        return "redirect:/product/getAllProducts";
    }

    @RequestMapping("/delProduct")
    public String delProduct(@RequestParam("id") Integer id){
        productService.delProduct(id);
        return "redirect:/product/getAllProducts";
    }

}
